package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.client.learning.LearningClient;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static com.tianji.common.constants.MqConstants.Key.ORDER_REFUND_KEY;

@Component
@Slf4j
@RequiredArgsConstructor
public class lessonChangListener {

    private final ILearningLessonService learningLessonService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "lesson.change.rlos.queue", durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listen(OrderBasicDTO order) {
        // 1.健壮性处理
        if (order == null || order.getUserId() == null || ObjectUtil.isEmpty(order.getCourseIds())) {
            log.warn("订单信息为空，订单id:{}", order);
            return;
        }

        // 2.添加课程
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.addLesson(order.getUserId(), order.getCourseIds());
    }




    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "lesson.delete.rlos.queue", durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_REFUND_KEY
    ))
    public void listenCancel(OrderBasicDTO order) {
        // 1.健壮性处理
        if (order == null || order.getUserId() == null || ObjectUtil.isEmpty(order.getCourseIds())) {
            log.warn("订单信息为空，订单id:{}", order);
            return;
        }
        log.debug("监听到用户{}的订单{}，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.deleteLessons(order.getUserId(), order.getCourseIds());
    }
}
